'use strict'
const path = require('path')
const {title} = require('./src/settings.js')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = title // page title

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || process.env.npm_config_port || 9528 // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: '/',
  outputDir: 'dist',
  assetsDir: `${process.env.VUE_APP_PREFIX || '.'}/static`,
  indexPath: `${process.env.VUE_APP_PREFIX || '.'}/index.html`,
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    }
    // before: require('./mock/mock-server.js')
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    // 正式环境不打包公共js 常用的公共js 排除掉，不打包 而是在index添加cdn，
    externals: ((isProd) => {
      return isProd ? {
        // vue: 'Vue',
        // vuex: 'Vuex',
        // 'vue-router': 'VueRouter',
        // axios: 'axios',
        // 'element-ui': 'ElementUI',
        'echarts': 'echarts',
        // 'lodash': {
        //   commonjs: 'lodash',
        //   amd: 'lodash',
        //   root: '_', // indicates global variable
        // },
        'moment': 'moment',
        // 'vue-baidu-map': 'vue-baidu-map'
        'vditor': 'Vditor'
      } : {}
    })(process.env.NODE_ENV === 'production')
  },
  // pages: {
  //   index: {
  //     // page 的入口
  //     entry: 'src/main.js',
  //     // 模板来源
  //     template: 'public/index.html',
  //     // 在 dist/index.html 的输出
  //     filename: 'index.html',
  //     // 当使用 title 选项时， template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
  //     // title: 'Index Page',
  //     // 在这个页面中包含的块，默认情况下会包含
  //     // 提取出来的通用 chunk 和 vendor chunk。
  //     chunks: ['chunk-libs', 'chunk-elementUI', 'chunk-commons', 'runtime', 'index']
  //   },
  //   // 当使用只有入口的字符串格式时，
  //   // 模板会被推导为 `public/subpage.html`
  //   // 并且如果找不到的话，就回退到 `public/index.html`。
  //   // 输出文件名会被推导为 `subpage.html`。
  //   // subpage: 'src/subpage/main.js'
  //   ui: {
  //     // page 的入口
  //     entry: 'src/ui.js',
  //     // 模板来源
  //     template: 'public/ui.html',
  //     // 在 dist/index.html 的输出
  //     filename: 'ui.html',
  //     chunks: ['chunk-libs', 'chunk-elementUI', 'chunk-commons', 'runtime', 'ui']
  //   }
  // },
  chainWebpack(config) {
    config.plugins.delete('preload') // TODO: need test
    config.plugins.delete('prefetch') // TODO: need test

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()
    // https://webpack.js.org/configuration/devtool/#development
    config.when(process.env.NODE_ENV === 'development', config => config.devtool('cheap-source-map'))
    const cdn = []
    if (process.env.NODE_ENV === 'production') {
      cdn.push( // 配置cdn给插件
        // vue: 'Vue',
        // '//cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.runtime.min.js',
        // vuex: 'Vuex',
        // '//cdn.bootcdn.net/ajax/libs/vuex/3.6.0/vuex.min.js',
        // 'vue-router': 'VueRouter',
        // '//cdn.bootcdn.net/ajax/libs/vue-router/3.0.3/vue-router.min.js',
        // axios: 'axios',
        // '//cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js',
        // 'element-ui': 'ELEMENT',
        // '/libs/element-ui/2.15.0/theme-chalk/index.min.css',
        // '/libs/element-ui/2.15.0/index.js',
        // '/libs/element-ui/2.15.0/locale/zh-CN.min.js',
        // 'echarts': 'echarts',
        // '//cdn.bootcdn.net/ajax/libs/echarts/4.9.0/echarts.min.js',
        '/libs/echarts/4.9.0/echarts.min.js',
        // 'lodash': 'lodash',
        // '/libs/lodash/4.17.21/lodash.min.js',
        // 'moment': 'moment',
        '/libs/moment/2.29.3/moment.min.js',
        '/libs/moment/2.29.3/zh-cn.js',
        // vue-baidu-map: 'vue-baidu-map'
        // '/libs/vue-baidu-map/0.21.22/index.js'
        // vditor : 'vditor'
        '/libs/vditor/3.8.15/dist/index.css',
        '/libs/vditor/3.8.15/dist/index.min.js'
        // https://cdn.bootcdn.net/ajax/libs/vditor/3.8.15/index.css
        // https://cdn.bootcdn.net/ajax/libs/vditor/3.8.15/index.min.css
        // https://cdn.bootcdn.net/ajax/libs/vditor/3.8.15/index.min.js
        // https://cdn.bootcdn.net/ajax/libs/vditor/3.8.15/method.min.js // 只接入渲染时依赖
      )
    }
    config.plugin('html').tap(args => {
      args[0].cdn = cdn // 配置cdn给插件
      return args
    })
    config.when(process.env.NODE_ENV !== 'development', config => {
      if (process.env.VUE_APP_ENV === 'production') {
        config
          .optimization
          .minimizer('terser')
          .tap(args => {
            Object.assign(args[0].terserOptions.compress, { // 生产模式 console.log 去除
              // warnings: false , // 默认 false
              // drop_console:  ,
              // drop_debugger: true, // 默认也是true
              pure_funcs: ['console.log']
            })
            return args
          })
      }
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [{
          // `runtime` must same as runtimeChunk name. default is `runtime`
          inline: /runtime\..*\.js$/
        }])
        .end()
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial' // only package third parties that are initially dependent
          },
          elementUI: {
            name: 'chunk-elementUI', // split elementUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      })
      config.optimization.runtimeChunk('single')

      config
        .plugin('CompressionWebpackPlugin')
        .use('compression-webpack-plugin', [{
          test: /\.(js|html|css)$/, // 正则匹配文件名
          threshold: 1024, // 对过1k的文件进行压缩
          deleteOriginalAssets: false // 是否删除原文件
        }])
        .end()
    })
  }
}
